package com.axter.app.gpspath;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.AssetManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.com.myapplication.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private LocationManager mLocManager;
    private Button btn_go;
    private Button btn_ready;
    private List<Point> points = new ArrayList<>();

    private int index = 0;
    private int count;
    private TextView tv_show;

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getTxt();
        setContentView(R.layout.activity_main);
        initViewIDs();
        initLocation();
    }

    private void initLocation() {
        mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocManager.addTestProvider(LocationManager.GPS_PROVIDER,
                "requiresNetwork" == "",
                "requiresSatellite" == "",
                "requiresCell" == "",
                "hasMonetaryCost" == "",
                "supportsAltitude" == "",
                "supportsSpeed" == "",
                "supportsBearing" == "",
                Criteria.NO_REQUIREMENT,
                Criteria.ACCURACY_COARSE);
        // 开启测试Provider
        mLocManager.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);

        mLocManager.setTestProviderStatus(LocationManager.GPS_PROVIDER,
                LocationProvider.AVAILABLE,
                null,
                System.currentTimeMillis());
    }

    private void getTxt() {
        AssetManager assetManager = getAssets();
        BufferedReader br = null;
        InputStream inputStream = null;
        try {
            inputStream = assetManager.open("paths.txt");
            br = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String temp;
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            Type collectionType = new TypeToken<List<Point>>() {
            }.getType();
            points = new Gson().fromJson(sb.toString(), collectionType);
            for (Point point : points) {
                point.setTime(point.getTime() * 1000);
                //random(point.getLat());
            }
            count = points.size();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initViewIDs() {
        btn_go = (Button) findViewById(R.id.btn_go);
        btn_ready = (Button) findViewById(R.id.btn_ready);
        tv_show = (TextView) findViewById(R.id.tv_show);

        btn_go.setOnClickListener(this);
        btn_ready.setOnClickListener(this);
    }

    private static final int TYPE_READY = 1;
    private static final int TYPE_GO = 2;
    private int type = TYPE_READY;

    private boolean isRunning = false;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_go:
                type = TYPE_GO;
                start();
                break;
            case R.id.btn_ready:
                type = TYPE_READY;
                start();
                break;
            case R.id.btn_huifu:
                index = (int) SPUtils.get(this, "pp", 0);
                start();
                break;
        }
    }

    private Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (index < count) {
                    tv_show.post(new Runnable() {
                        @Override
                        public void run() {
                            tv_show.setText("" + index);
                        }
                    });
                    // 创建新的Location对象，并设定必要的属性值
                    Location newLocation = new Location(LocationManager.GPS_PROVIDER);
                    newLocation.setLatitude(random(points.get(index).getLat()));
                    newLocation.setLongitude(random(points.get(index).getLon()));
                    newLocation.setAccuracy(random());// 精度
                    newLocation.setAltitude(random());// 海拔
                    newLocation.setTime(System.currentTimeMillis());
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        newLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
                    }
                    // 设置最新位置
                    mLocManager.setTestProviderLocation(LocationManager.GPS_PROVIDER, newLocation);
                    if (type == TYPE_GO) {
                        index++;
                        SPUtils.put(MainActivity.this, "pp", index);
                        Thread.sleep(points.get(index).getTime() - points.get(index - 1).getTime());
                    } else if (type == TYPE_READY) {
                        Thread.sleep(1000);
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    private void start() {
        if (!isRunning) {
            isRunning = true;
            thread.start();
        }
    }

    Random random = new Random();

    private int random() {
        return random.nextInt(3) + 2;
    }

    private double random(double value) {
        int rr = random.nextInt(5) + 1;
        double dd = value + rr * 0.00001d;

        //System.out.println(value + "|" + rr + "|" + dd);
        return dd;
    }
}
